#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

DESTDIR=$(mktemp -d)
while [[ ! -b /dev/$disk ]] ; do
    echo $(ls /sys/block/* | grep "[0-9]$")
    echo -n "Rootfs partition >>> "
    read disk
done

# Unmount the partition if it is already mounted
umount -lf /dev/$disk >/dev/null 2>&1 || true

# Mount the partition to DESTDIR
mount /dev/$disk "$DESTDIR"

# Prompt the user for a new password
while true; do
    if [[ "$pass1" == "$pass2" && -n "$pass1" ]]; then
        break
    else
        read -s -p "Enter new password: " pass1; echo
        read -s -p "Confirm password: " pass2; echo
    fi
done
if [[ "$pass1" == "" ]] ; then
    # Get the username of the first non-root user
    user=$(grep "^.*:x:1000:" "$DESTDIR"/etc/passwd | cut -f 1 -d ':')
fi
# Change the password of the user in the chroot environment
chroot "$DESTDIR" usermod -p $(openssl passwd -6 "$pass1") "$user"

# Unmount the partition
umount -lf "$DESTDIR" >/dev/null 2>&1
